#include "com_console.h"

#include <stdio.h>
#include <time.h>
#include <stdarg.h>

#define CONSOLE_PATH "console.txt"
#define MSG_NORMAL	0
#define MSG_WARNING	1
#define MSG_ERROR	2
#define MSG_FATAL	3

#define ECHO_SEQUENCE(msgType) 	\
	va_list ap;\
	char msg[2048];\
	va_start(ap,fmt);\
	vsprintf(msg,fmt,ap);\
	va_end(ap);\
	outputStr(msg,msgType);

static bool consoleOpen = false;

static void resetConsole();

static void outputStr(char * str, int msgType)
{
	if (!consoleOpen)
		resetConsole();

	FILE *f = fopen(CONSOLE_PATH,"at");
	if (!f)
		return;

	time_t rawtime;
	struct tm * timeinfo;
	time ( &rawtime );
	timeinfo = localtime ( &rawtime );
	char buffer [128];

	strftime (buffer,128,"%d/%m/%Y %H:%M:%S",timeinfo);

	fprintf(f,"[%s]  %s\n",buffer,str);
	fclose(f);
}

static void resetConsole()
{
	FILE *f=fopen(CONSOLE_PATH,"wt");
	fclose(f);
	consoleOpen = true;

	outputStr("Console started",MSG_NORMAL);
}

void com_print(char *fmt, ...)
{
	ECHO_SEQUENCE(MSG_NORMAL)
}

void com_warn(char *fmt, ...)
{
	ECHO_SEQUENCE(MSG_WARNING);
}

void com_error(char *fmt, ...)
{
	ECHO_SEQUENCE(MSG_ERROR);
}

void com_fatal(char *fmt, ...)
{
	ECHO_SEQUENCE(MSG_FATAL);
}